package com.sky.controller.admin;

import com.sky.dto.CategoryPageQueryDTO;
import com.sky.dto.DishDTO;
import com.sky.dto.DishPageQueryDTO;
import com.sky.entity.Dish;
import com.sky.result.PageResult;
import com.sky.result.Result;
import com.sky.service.DishService;
import com.sky.vo.DishVO;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Set;

@RestController
@RequestMapping("/admin/dish")
@Slf4j
@Api(tags = "菜品接口")
public class DishController {
    @Autowired
    private DishService dishService;
    @Autowired
    private RedisTemplate redisTemplate;
    /**
     * 保存菜品
     */
    @PostMapping
    @ApiOperation("保存菜品")
    public Result<String> save(@RequestBody DishDTO dishDTO) {
        log.info("保存菜品:{}", dishDTO);
        dishService.save(dishDTO);

        //新增菜品后，需要删除对应分类下的所有缓存，重新生成数据
        redisTemplate.delete("dish_" + dishDTO.getCategoryId());
        return Result.success();
    }

    /**
     * 分页查询
     */
    @GetMapping("/page")
    @ApiOperation("分页查询菜品")
    public Result<PageResult> page(DishPageQueryDTO dishPageQueryDTO) {
        log.info("分页查询菜品：{}", dishPageQueryDTO);
        PageResult pageResult = dishService.page(dishPageQueryDTO);
        return Result.success(pageResult);
    }

    /**
     * 删除菜品
     */
    @DeleteMapping
    @ApiOperation("删除菜品")
    public Result delete(String[] ids) {
        log.info("删除菜品：{}", ids);
        dishService.deleteBatch(ids);

        //删除菜品，可以涉及到多个类别的变更，自己全部删除缓存
        clearCache();
        return Result.success();
    }

    /**
     * 根据菜品id查询菜品
     */
    @GetMapping("/{id}")
    @ApiOperation("根据菜品id查询菜品")
    public Result<DishVO> getByDishId(@PathVariable Integer id){
        log.info("根据菜品id查询菜品：{}", id);
        DishVO dishVO = dishService.getDishById(id);
        return Result.success(dishVO);
    }

    @PutMapping
    @ApiOperation("修改菜品")
    public Result update(@RequestBody DishDTO dishDTO) {
        log.info("修改菜品：{}", dishDTO);
        dishService.updateDish(dishDTO);

        //修改菜品的时候可能会变更菜品的类别，为了简化，直接全部删除缓存
        clearCache();
        return Result.success();
    }

    @GetMapping("/list")
    @ApiOperation("根据分类id获取菜品")
    public Result<List<Dish>> getByCategoryId(@RequestParam Integer categoryId) {
        log.info("根据分类id获取菜品：{}", categoryId);
        List<Dish> dishes = dishService.getDishByCategoryId(categoryId);
        return Result.success(dishes);
    }

    private void clearCache() {
        Set keys = redisTemplate.keys("dish_*");
        redisTemplate.delete(keys);
    }
}
